package com.qulai.web.controller.amazon_us;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qulai.amazon_us.domain.amazon_us.AmazonUsContent;
import com.qulai.amazon_us.domain.amazon_us.AmazonUsPost;
import com.qulai.amazon_us.domain.amazon_us.AmazonUsRecord;
import com.qulai.amazon_us.domain.basic.Image;
import com.qulai.amazon_us.service.amazon_us.IAmazonUsContentService;
import com.qulai.amazon_us.service.amazon_us.IAmazonUsPostService;
import com.qulai.amazon_us.service.amazon_us.IAmazonUsRecordService;
import com.qulai.amazon_us.service.basic.IImageService;
import com.qulai.amazon_us.util.basic.LlmApiUtil;
import com.qulai.common.annotation.Anonymous;
import com.qulai.common.annotation.Log;
import com.qulai.common.core.controller.BaseController;
import com.qulai.common.core.domain.AjaxResult;
import com.qulai.common.core.page.TableDataInfo;
import com.qulai.common.enums.BusinessType;
import com.qulai.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.qulai.amazon_us.util.basic.LlmApiUtil.AMAZON_US_POST_PROMPT;

/**
 * 上传POSTController
 *
 * @author hunan
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/amazon_us/post")
public class AmazonUsPostController extends BaseController {
    @Autowired
    private IAmazonUsPostService amazonUsPostService;
    @Autowired
    private IAmazonUsRecordService amazonUsRecordService;
    @Autowired
    private IImageService imageService;
    @Autowired
    private IAmazonUsContentService contentService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    /**
     * 查询上传POST列表
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:post:list')")
    @GetMapping("/list")
    public TableDataInfo list(AmazonUsPost amazonUsPost) {
        startPage();
        List<AmazonUsPost> list = amazonUsPostService.selectAmazonUsPostList(amazonUsPost);
        return getDataTable(list);
    }

    /**
     * 导出上传POST列表
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:post:export')")
    @Log(title = "上传POST", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AmazonUsPost amazonUsPost) {
        List<AmazonUsPost> list = amazonUsPostService.selectAmazonUsPostList(amazonUsPost);
        ExcelUtil<AmazonUsPost> util = new ExcelUtil<AmazonUsPost>(AmazonUsPost.class);
        util.exportExcel(response, list, "上传POST数据");
    }

    /**
     * 获取上传POST详细信息
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:post:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(amazonUsPostService.selectAmazonUsPostById(id));
    }


    /**
     * 获取ASIN的图片信息: 分表前的版本
     */
//    @Anonymous
//    @GetMapping(value = "/images/{mainAsin}")
//    public AjaxResult getImgByAsin(@PathVariable("mainAsin") String mainAsin) {
//        AmazonUsRecord amazonUsRecord = amazonUsRecordService.selectAmazonUsRecordByAsin(mainAsin, "");
//        if (amazonUsRecord == null) {
//            throw new RuntimeException("主ASIN不存在,或还未同步");
//        }
//        AmazonUsPost query = new AmazonUsPost();
//        query.setMainAsin(mainAsin.trim());
//        List<AmazonUsPost> amazonUsPosts = amazonUsPostService.selectAmazonUsPostList(query);
//        if (!amazonUsPosts.isEmpty()) {
//            throw new RuntimeException("该主ASIN已经发过帖子了");
//        }
//        if (amazonUsRecord.getQuantity() < 3) {
//            throw new RuntimeException("主ASIN的库存为:" + amazonUsRecord.getQuantity() + ",请选库存大于该数的做为主ASIN");
//        }
//        //目前还只有原图
//        Image image = imageService.selectImageByBasicId(amazonUsRecord.getBasicId());
//        // 提取所有副图URL并过滤掉null或空字符串
//
//        // 如果需要，也可以转换成ArrayList
//        ArrayList<String> resultList = Stream.of(image.getMainImage(),
//                        image.getOtherImageUrl1(), image.getOtherImageUrl2(), image.getOtherImageUrl3(),
//                        image.getOtherImageUrl4(), image.getOtherImageUrl5(), image.getOtherImageUrl6(),
//                        image.getOtherImageUrl7(), image.getOtherImageUrl8(), image.getOtherImageUrl9(),
//                        image.getOtherImageUrl10(), image.getOtherImageUrl11(), image.getOtherImageUrl12(),
//                        image.getOtherImageUrl13(), image.getOtherImageUrl14(), image.getOtherImageUrl15()
//                )
//                .filter(url -> url != null && !url.isEmpty()).collect(Collectors.toCollection(ArrayList::new));
//        // 返回成功响应，携带图片列表
//        return success(resultList);
//    }

    /**
     * 获取ASIN的图片信息： 分表之后的版本
     */
    @Anonymous
    @GetMapping(value = "/images/")
    public AjaxResult getImgByAsin(AmazonUsPost amazonUsPost) {

        if(amazonUsPost.getMainAsin() == null || amazonUsPost.getMainAsin().equals("")){
            throw new RuntimeException("主ASIN不能为空");
        }

        if(amazonUsPost.getShop() == null || amazonUsPost.getShop().equals("")){
            throw new RuntimeException("店铺不能为空");
        }

        String mainAsin = amazonUsPost.getMainAsin();
        String shop = amazonUsPost.getShop();

        AmazonUsRecord amazonUsRecord = amazonUsRecordService.selectAmazonUsRecordByAsin_v2(mainAsin, shop);
        if (amazonUsRecord == null) {
            throw new RuntimeException("主ASIN不存在,或还未同步");
        }
        AmazonUsPost query = new AmazonUsPost();
        query.setMainAsin(mainAsin.trim());
        List<AmazonUsPost> amazonUsPosts = amazonUsPostService.selectAmazonUsPostList(query);
        if (!amazonUsPosts.isEmpty()) {
            throw new RuntimeException("该主ASIN已经发过帖子了");
        }
        if (amazonUsRecord.getQuantity() < 3) {
            throw new RuntimeException("主ASIN的库存为:" + amazonUsRecord.getQuantity() + ",请选库存大于该数的做为主ASIN");
        }
        //目前还只有原图
        Image image = imageService.selectImageByBasicId(amazonUsRecord.getBasicId());
        // 提取所有副图URL并过滤掉null或空字符串

        // 如果需要，也可以转换成ArrayList
        ArrayList<String> resultList = Stream.of(image.getMainImage(),
                        image.getOtherImageUrl1(), image.getOtherImageUrl2(), image.getOtherImageUrl3(),
                        image.getOtherImageUrl4(), image.getOtherImageUrl5(), image.getOtherImageUrl6(),
                        image.getOtherImageUrl7(), image.getOtherImageUrl8(), image.getOtherImageUrl9(),
                        image.getOtherImageUrl10(), image.getOtherImageUrl11(), image.getOtherImageUrl12(),
                        image.getOtherImageUrl13(), image.getOtherImageUrl14(), image.getOtherImageUrl15()
                )
                .filter(url -> url != null && !url.isEmpty()).collect(Collectors.toCollection(ArrayList::new));
        // 返回成功响应，携带图片列表
        return success(resultList);
    }

    /**
     * 新增上传POST
     */
//    @PreAuthorize("@ss.hasPermi('amazon_us:post:add')")
//    @Log(title = "上传POST", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody AmazonUsPost amazonUsPost) {
//        amazonUsPost.setMainAsin(amazonUsPost.getMainAsin().trim());
//        AmazonUsRecord amazonUsRecord = amazonUsRecordService.selectAmazonUsRecordByAsin(amazonUsPost.getMainAsin(), amazonUsPost.getShop());
//        if (amazonUsRecord == null) {
//            throw new RuntimeException("主ASIN不存在,或还未同步");
//        }
//        if (amazonUsRecord.getQuantity() < 4) {
//            throw new RuntimeException("主ASIN的库存为:" + amazonUsRecord.getQuantity() + ",请选库存大于该值的做为主ASIN");
//        }
//        if (null != amazonUsPost.getOtherAsin() && !amazonUsPost.getOtherAsin().isEmpty()) {
//            if (!amazonUsPost.getOtherAsin().matches("[A-Za-z0-9,]*")) {
//                throw new RuntimeException("副ASIN包含非法字符，只允许字母、数字和英文半角逗号");
//            }
//            // 使用英文半角逗号分割字符串
//            String[] asins = amazonUsPost.getOtherAsin().split(",");
//            // 检查ASIN数量是否超过4个
//            if (asins.length > 4) {
//                throw new RuntimeException("ASIN数量超过4个");
//            }
//            // 验证每个ASIN是否为10位
//            for (String asin : asins) {
//                if (asin.length() != 10) {
//                    throw new RuntimeException("无效的ASIN: " + asin + ",长度不为10");
//                }
//                AmazonUsRecord other = amazonUsRecordService.selectAmazonUsRecordByAsin(asin, amazonUsPost.getShop());
//                if (other == null) {
//                    throw new RuntimeException("副业ASIN不存在,或还未同步,不存在的ASIN:" + asin);
//                }
//                if (!other.getBrand().equals(amazonUsRecord.getBrand()) || !other.getShop().equals(amazonUsRecord.getShop())) {
//                    throw new RuntimeException("副业ASIN需要与主ASIN同店铺同品牌,不匹配的副ASIN:" + asin + ",brand:" + other.getBrand() + ",shop:" + other.getShop() + ".主ASIN brand:" + amazonUsRecord.getBrand() + ",shop:" + amazonUsRecord.getShop());
//                }
//            }
//        }
//        amazonUsPost.setBrand(amazonUsRecord.getBrand());
//        amazonUsPost.setShop(amazonUsRecord.getShop());
//        amazonUsPost.setUpdateBy(getUsername());
//        amazonUsPost.setStatus(0L);
//        //如果没有填写则AI生成
//        threadPoolTaskExecutor.execute(() -> {
//            if (amazonUsPost.getCaption() == null || amazonUsPost.getCaption().isEmpty() || amazonUsPost.getCaption().length() < 10) {
//                AmazonUsContent amazonUsContent = new AmazonUsContent();
//                amazonUsContent.setBasicId(amazonUsRecord.getBasicId());
//                amazonUsContent.setBrand(amazonUsRecord.getBrand());
//                List<AmazonUsContent> amazonUsContents = contentService.selectAmazonUsContentList(amazonUsContent);
//                if (amazonUsContents.isEmpty()) {
//                    amazonUsContent.setBrand(null);
//                    amazonUsContents = contentService.selectAmazonUsContentList(amazonUsContent);
//                }
//                if (!amazonUsContents.isEmpty()) {
//                    try {
//                        JSONObject jsonObject = JSON.parseObject(amazonUsContents.get(0).getContent());
//                        String description = filterHtmlData(jsonObject.getString("product_description"));
//                        JSONObject res = (JSONObject) LlmApiUtil.openaiRsp(true, description, AMAZON_US_POST_PROMPT, null, 3);
//                        String title = res.getString("title");
//                        if (title == null || title.length() < 5) {
//                            amazonUsPost.setStatus(3L);
//                            amazonUsPost.setRemark("AI犯错 解析文本不正确");
//                        } else {
//                            amazonUsPost.setCaption(title);
//                        }
//                    } catch (Exception e) {
//                        amazonUsPost.setStatus(3L);
//                        amazonUsPost.setRemark("ASIN对应文案解析失败或AI请求失败2次");
//                    }
//                } else {
//                    amazonUsPost.setStatus(3L);
//                    amazonUsPost.setRemark("没有找到对应的制表文案");
//                }
//            }
//            amazonUsPostService.insertAmazonUsPost(amazonUsPost);
//        });
//
//        return toAjax(1);
//    }

    @PreAuthorize("@ss.hasPermi('amazon_us:post:add')")
    @Log(title = "上传POST", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AmazonUsPost amazonUsPost) {
        amazonUsPost.setMainAsin(amazonUsPost.getMainAsin().trim());
        amazonUsPost.setShop(amazonUsPost.getShop().trim());

        AmazonUsRecord amazonUsRecord = amazonUsRecordService.selectAmazonUsRecordByAsin_v2(amazonUsPost.getMainAsin(), amazonUsPost.getShop());
        if (amazonUsRecord == null) {
            throw new RuntimeException("主ASIN不存在,或还未同步");
        }
        if (amazonUsRecord.getQuantity() < 4) {
            throw new RuntimeException("主ASIN的库存为:" + amazonUsRecord.getQuantity() + ",请选库存大于该值的做为主ASIN");
        }
        if (null != amazonUsPost.getOtherAsin() && !amazonUsPost.getOtherAsin().isEmpty()) {
            if (!amazonUsPost.getOtherAsin().matches("[A-Za-z0-9,]*")) {
                throw new RuntimeException("副ASIN包含非法字符，只允许字母、数字和英文半角逗号");
            }
            // 使用英文半角逗号分割字符串
            String[] asins = amazonUsPost.getOtherAsin().split(",");
            // 检查ASIN数量是否超过4个
            if (asins.length > 4) {
                throw new RuntimeException("ASIN数量超过4个");
            }
            // 验证每个ASIN是否为10位
            for (String asin : asins) {
                if (asin.length() != 10) {
                    throw new RuntimeException("无效的ASIN: " + asin + ",长度不为10");
                }
                AmazonUsRecord other = amazonUsRecordService.selectAmazonUsRecordByAsin_v2(asin, amazonUsPost.getShop());
                if (other == null) {
                    throw new RuntimeException("副业ASIN不存在,或还未同步,不存在的ASIN:" + asin);
                }
                if (!other.getBrand().equals(amazonUsRecord.getBrand()) || !other.getShop().equals(amazonUsRecord.getShop())) {
                    throw new RuntimeException("副业ASIN需要与主ASIN同店铺同品牌,不匹配的副ASIN:" + asin + ",brand:" + other.getBrand() + ",shop:" + other.getShop() + ".主ASIN brand:" + amazonUsRecord.getBrand() + ",shop:" + amazonUsRecord.getShop());
                }
            }
        }
        amazonUsPost.setBrand(amazonUsRecord.getBrand());
        amazonUsPost.setShop(amazonUsRecord.getShop());
        amazonUsPost.setUpdateBy(getUsername());
        amazonUsPost.setStatus(0L);
        //如果没有填写则AI生成
        threadPoolTaskExecutor.execute(() -> {
            if (amazonUsPost.getCaption() == null || amazonUsPost.getCaption().isEmpty() || amazonUsPost.getCaption().length() < 10) {
                AmazonUsContent amazonUsContent = new AmazonUsContent();
                amazonUsContent.setBasicId(amazonUsRecord.getBasicId());
                amazonUsContent.setBrand(amazonUsRecord.getBrand());
                List<AmazonUsContent> amazonUsContents = contentService.selectAmazonUsContentList(amazonUsContent);
                if (amazonUsContents.isEmpty()) {
                    amazonUsContent.setBrand(null);
                    amazonUsContents = contentService.selectAmazonUsContentList(amazonUsContent);
                }
                if (!amazonUsContents.isEmpty()) {
                    try {
                        JSONObject jsonObject = JSON.parseObject(amazonUsContents.get(0).getContent());
                        String description = filterHtmlData(jsonObject.getString("product_description"));
                        JSONObject res = (JSONObject) LlmApiUtil.openaiRsp(true, description, AMAZON_US_POST_PROMPT, null, 3);
                        String title = res.getString("title");
                        if (title == null || title.length() < 5) {
                            amazonUsPost.setStatus(3L);
                            amazonUsPost.setRemark("AI犯错 解析文本不正确");
                        } else {
                            amazonUsPost.setCaption(title);
                        }
                    } catch (Exception e) {
                        amazonUsPost.setStatus(3L);
                        amazonUsPost.setRemark("ASIN对应文案解析失败或AI请求失败2次");
                    }
                } else {
                    amazonUsPost.setStatus(3L);
                    amazonUsPost.setRemark("没有找到对应的制表文案");
                }
            }
            amazonUsPostService.insertAmazonUsPost(amazonUsPost);
        });

        return toAjax(1);
    }

    /**
     * 修改上传POST
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:post:edit')")
    @Log(title = "上传POST", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AmazonUsPost amazonUsPost) {
        amazonUsPost.setUpdateBy(getUsername());
        return toAjax(amazonUsPostService.updateAmazonUsPost(amazonUsPost));
    }

    /**
     * 删除上传POST
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:post:remove')")
    @Log(title = "上传POST", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(amazonUsPostService.deleteAmazonUsPostByIds(ids));
    }


    public static String filterHtmlData(String htmlContent) {
        if (htmlContent == null || htmlContent.isEmpty()) {
            return "";
        }

        // 替换HTML标签为换行符
        String cleanedText = htmlContent.replaceAll("<[^>]+>", "\n");

        // 移除非ASCII字符
        String cleanedWithoutUnicode = Pattern.compile("[^\\x00-\\x7F]")
                .matcher(cleanedText)
                .replaceAll("");

        // 移除HTML实体
        String finalCleanedText = Pattern.compile("&#\\d+;")
                .matcher(cleanedWithoutUnicode)
                .replaceAll("");

        // 处理首尾空白和换行符
        String result = finalCleanedText.trim();
        result = result.replace("\n\n\n", "\n").replace("\n\n", "\n");

        return result;
    }
}
